package com.wisdudu.blank.ui.home.city;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.wisdudu.blank.R;
import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.bean.CityInfo;
import com.wisdudu.blank.data.bean.SortModel;
import com.wisdudu.blank.data.bean.UserInfo;
import com.wisdudu.blank.data.repo.UserRepo;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.NextErrorSubscriber;
import com.wisdudu.blank.databinding.FragmentSelecteCityBinding;
import com.wisdudu.frame.base.BaseFragment;
import com.wisdudu.blank.support.rxbus.RxBus;
import com.wisdudu.blank.support.util.PinyinComparator;
import com.wisdudu.blank.support.util.ToastUtil;
import com.wisdudu.blank.ui.common.ClearEditText;
import com.wisdudu.blank.ui.common.SideBar;
import com.wisdudu.blank.ui.common.adapter.SortAdapter;
import com.wisdudu.frame.support.util.CharacterParser;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.Subscriber;

/**
 * 城市列表
 * Created by wk on 2015/7/2.
 */
public class SelectAddressFragment extends BaseFragment {
    private PinyinComparator pinyinComparator;
    private SideBar sideBar;
    private TextView mTvDialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> sourceDateList = new ArrayList<>();
    private ListView sortListView;
    private FragmentSelecteCityBinding mBinding;
    private UserRepo userRepo;
    private int provinceid;
    private int region;

    public static BaseFragment newIntance(int provinceid, int region) {
        Bundle bundle = new Bundle();
        bundle.putInt("provinceid", provinceid);
        bundle.putInt("region", region);
        SelectAddressFragment fragment = new SelectAddressFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initBinding(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_selecte_city, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initToolbar(getToolbar(), "选择省份");
        userRepo = Injection.provideUserRepo();
        provinceid = getArguments().getInt("provinceid");
        region = getArguments().getInt("region");
        initView();
        userRepo.getCity(provinceid, region, 2)
                .compose(bindToLifecycle()).subscribe(new NextErrorSubscriber<List<CityInfo>>() {
            @Override
            public void onNext(List<CityInfo> cityInfos) {
                sourceDateList.clear();
                sourceDateList.addAll(filledData(cityInfos));
                Collections.sort(sourceDateList, pinyinComparator);
                adapter.updateListView(sourceDateList);
            }
        });
    }

    private void initView() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar = mBinding.sidrbar;
        mTvDialog = mBinding.dialog;
        sideBar.setTextView(mTvDialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });
        sortListView = mBinding.countryLvcountry;
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (region != 4) {
                    addFragment(SelectAddressFragment.newIntance(sourceDateList.get(position).getBrandid(), region + 1));
                } else {
                    userRepo.setVillage(sourceDateList.get(position).getBrandid())
                            .compose(bindToLifecycle()).subscribe(new Subscriber<UserInfo>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastUtil.INSTANCE.netError();
                        }

                        @Override
                        public void onNext(UserInfo userInfoAbs) {
                            ToastUtil.INSTANCE.toast("切换成功");
                            RxBus.getDefault().post(sourceDateList.get(position));
                            removeFragment();
                            getActivity().finish();
                        }
                    });
                }
            }
        });
        adapter = new SortAdapter(getActivity(), sourceDateList);
        sortListView.setAdapter(adapter);

        mClearEditText = mBinding.filterEdit;
        mClearEditText.setVisibility(View.VISIBLE);
        mClearEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (getActivity().getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {
                    sideBar.setVisibility(View.GONE);
                } else {
                    sideBar.setVisibility(View.VISIBLE);
                }
            }
        });
        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 为ListView填充数据
     *
     * @param cityInfos
     * @return
     */
    private List<SortModel> filledData(List<CityInfo> cityInfos) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < cityInfos.size(); i++) {
            SortModel sortModel = new SortModel();
            CityInfo cityInfo = cityInfos.get(i);
            if (region == 4) {
                sortModel.setName(cityInfo.getVillage());
                sortModel.setBrandid(cityInfo.getVillageid());
            } else {
                sortModel.setName(cityInfo.getCity());
                sortModel.setBrandid(cityInfo.getCityid());
            }
            if (sortModel.getName() != null) {             //判断该字段是否为null
                //汉字转换成拼音
                String pinyin = characterParser.getSelling(sortModel.getName());
                String sortString = "";
                if (sortModel.getName().contains("重庆")) {
                    sortString = "C";
                } else {
                    sortString = pinyin.substring(0, 1).toUpperCase();
                }
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    sortModel.setSortLetters(sortString.toUpperCase());
                } else {
                    sortModel.setSortLetters("#");
                }
                mSortList.add(sortModel);
            }
        }
        return mSortList;
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : sourceDateList) {
                String name = sortModel.getName();

                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

}
